package com.ruoyi.tzai.service.ai.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.tzai.service.ai.IAIService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 阿里云通义千问AI服务实现
 * 使用通义千问API (兼容OpenAI格式)
 *
 * @author tzai
 * @date 2025-10-28
 */
@Service("aliyunAIService")
public class AliyunAIServiceImpl implements IAIService
{
    private static final Logger log = LoggerFactory.getLogger(AliyunAIServiceImpl.class);

    private static final String DEFAULT_ENDPOINT = "https://dashscope.aliyuncs.com/compatible-mode/v1";
    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");

    private String apiKey;
    private String apiEndpoint;
    private String modelName;
    private OkHttpClient httpClient;

    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
        initHttpClient();
    }

    public void setApiEndpoint(String apiEndpoint) {
        this.apiEndpoint = apiEndpoint;
    }

    public void setModelName(String modelName) {
        this.modelName = modelName;
    }

    @Override
    public String getModelName() {
        return modelName != null ? modelName : "qwen-max";
    }

    /**
     * 初始化HTTP客户端
     */
    private void initHttpClient() {
        if (httpClient == null) {
            httpClient = new OkHttpClient.Builder()
                .connectTimeout(600, TimeUnit.SECONDS)
                .readTimeout(6000, TimeUnit.SECONDS)  // 全文处理耗时更长，读超时放宽到10分钟
                .writeTimeout(1200, TimeUnit.SECONDS)
                .build();
        }
    }

    /**
     * 调用通义千问API
     */
    private String callQwenAPI(String systemPrompt, String userPrompt) throws IOException {
        if (apiKey == null || apiKey.isEmpty()) {
            throw new RuntimeException("未配置API Key");
        }

        if (httpClient == null) {
            initHttpClient();
        }

        String endpoint = apiEndpoint != null ? apiEndpoint : DEFAULT_ENDPOINT;
        String model = modelName != null ? modelName : "qwen-max";

        // 构造请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", model);

        JSONArray messages = new JSONArray();

        // 添加系统消息
        if (systemPrompt != null && !systemPrompt.isEmpty()) {
            JSONObject systemMsg = new JSONObject();
            systemMsg.put("role", "system");
            systemMsg.put("content", systemPrompt);
            messages.add(systemMsg);
        }

        // 添加用户消息
        JSONObject userMsg = new JSONObject();
        userMsg.put("role", "user");
        userMsg.put("content", userPrompt);
        messages.add(userMsg);

        requestBody.put("messages", messages);

        // 发送请求
        RequestBody body = RequestBody.create(requestBody.toJSONString(), JSON_MEDIA_TYPE);
        Request request = new Request.Builder()
            .url(endpoint + "/chat/completions")
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .post(body)
            .build();

        log.info("调用通义千问API: {}", endpoint);

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "无响应体";
                log.error("API调用失败: HTTP {}, {}", response.code(), errorBody);
                throw new IOException("API调用失败: HTTP " + response.code());
            }

            String responseBody = response.body().string();
            JSONObject jsonResponse = JSON.parseObject(responseBody);

            // 提取AI回复内容
            JSONArray choices = jsonResponse.getJSONArray("choices");
            if (choices != null && !choices.isEmpty()) {
                JSONObject firstChoice = choices.getJSONObject(0);
                JSONObject message = firstChoice.getJSONObject("message");
                return message.getString("content");
            }

            throw new IOException("无法从API响应中提取内容");
        }
    }

    @Override
    public String generateSummary(String content, String language) {
        log.info("生成摘要 - 语言: {}, 内容长度: {}", language, content.length());

        // 检查API Key
        if (apiKey == null || apiKey.isEmpty()) {
            log.warn("未配置API Key，使用模拟摘要");
            if ("en".equals(language)) {
                return "This is a simulated summary. Please configure API Key to use real AI service.";
            } else {
                return "这是模拟摘要。请配置API Key以使用真实AI服务。";
            }
        }

        try {
            // 构造提示词
            String systemPrompt = "en".equals(language)
                ? "You are a professional news summarizer. Generate a concise summary of the given content in English, around 50-100 words."
                : "你是一位专业的新闻摘要生成专家。请为给定的内容生成简洁的中文摘要，50-100字左右。";

            String userPrompt = "en".equals(language)
                ? "Please summarize the following content:\n\n" + content
                : "请为以下内容生成摘要：\n\n" + content;

            // 调用API
            String summary = callQwenAPI(systemPrompt, userPrompt);
            log.info("摘要生成成功，长度: {}", summary.length());
            return summary;

        } catch (Exception e) {
            log.error("生成摘要失败", e);
            return "摘要生成失败: " + e.getMessage();
        }
    }

    @Override
    public String smartSegmentation(String content, String language) {
        log.info("智能断句 - 语言: {}, 内容长度: {}", language, content.length());

        // 检查API Key
        if (apiKey == null || apiKey.isEmpty()) {
            log.warn("未配置API Key，使用基础断句");
            return performBasicSegmentation(content, language);
        }

        try {
            // 构造提示词
            String systemPrompt = "en".equals(language)
                ? "You are a text segmentation expert. Split the given text into natural, well-structured sentences suitable for text-to-speech. Return ONLY a JSON array format: [{\"index\":0,\"text\":\"sentence1\"},{\"index\":1,\"text\":\"sentence2\"}]"
                : "你是文本分段专家。请将给定的文本拆分为自然、结构良好的句子，适合语音合成。只返回JSON数组格式：[{\"index\":0,\"text\":\"句子1\"},{\"index\":1,\"text\":\"句子2\"}]";

            String userPrompt = "en".equals(language)
                ? "Split this text into sentences:\n\n" + content
                : "将以下文本分句：\n\n" + content;

            // 调用API
            String result = callQwenAPI(systemPrompt, userPrompt);

            // 尝试解析JSON
            try {
                // 清理可能的markdown代码块标记
                String cleanResult = result.trim();
                if (cleanResult.startsWith("```json")) {
                    cleanResult = cleanResult.substring(7);
                }
                if (cleanResult.startsWith("```")) {
                    cleanResult = cleanResult.substring(3);
                }
                if (cleanResult.endsWith("```")) {
                    cleanResult = cleanResult.substring(0, cleanResult.length() - 3);
                }
                cleanResult = cleanResult.trim();

                JSONArray sentences = JSON.parseArray(cleanResult);
                log.info("智能断句完成，共{}句", sentences.size());
                return sentences.toJSONString();
            } catch (Exception e) {
                log.warn("AI返回格式解析失败，使用基础断句", e);
                return performBasicSegmentation(content, language);
            }

        } catch (Exception e) {
            log.error("智能断句失败，使用基础断句", e);
            return performBasicSegmentation(content, language);
        }
    }

    /**
     * 基础断句（不使用AI）
     */
    private String performBasicSegmentation(String content, String language) {
        JSONArray sentences = new JSONArray();

        // 简单的断句逻辑：按句号、问号、感叹号分割
        String[] parts;
        if ("en".equals(language)) {
            parts = content.split("(?<=[.!?])\\s+");
        } else {
            parts = content.split("(?<=[。！？])");
        }

        int index = 0;
        for (String part : parts) {
            if (part.trim().isEmpty()) continue;

            JSONObject sentence = new JSONObject();
            sentence.put("index", index++);
            sentence.put("text", part.trim());
            sentences.add(sentence);
        }

        log.info("基础断句完成，共{}句", sentences.size());
        return sentences.toJSONString();
    }

    @Override
    public String translate(String content, String sourceLang, String targetLang) {
        log.info("翻译文本 - 源语言: {}, 目标语言: {}, 内容长度: {}",
            sourceLang, targetLang, content.length());

        // 检查API Key
        if (apiKey == null || apiKey.isEmpty()) {
            log.warn("未配置API Key，跳过翻译");
            if ("en".equals(targetLang)) {
                return "[Translation skipped - API Key not configured] " + content;
            } else {
                return "【翻译已跳过 - 未配置API Key】" + content;
            }
        }

        try {
            // 构造提示词
            String sourceLangName = "cn".equals(sourceLang) ? "Chinese" : "English";
            String targetLangName = "cn".equals(targetLang) ? "Chinese" : "English";

            String systemPrompt = String.format(
                "You are a professional translator. Translate the given text from %s to %s. Keep the translation accurate and natural. Return ONLY the translated text without any explanation.",
                sourceLangName, targetLangName
            );

            String userPrompt = content;

            // 调用API
            String translation = callQwenAPI(systemPrompt, userPrompt);
            log.info("翻译完成，结果长度: {}", translation.length());
            return translation;

        } catch (Exception e) {
            log.error("翻译失败", e);
            return "翻译失败: " + e.getMessage();
        }
    }

    @Override
    public BilingualSummary generateBilingualSummary(String content, String sourceLang) {
        log.info("生成双语摘要和断句 - 源语言: {}, 内容长度: {}", sourceLang, content.length());

        BilingualSummary result = new BilingualSummary();
        String processMode = "summary"; // 默认摘要模式
        if (content != null && content.length() > 8000) {
            log.warn("长文本警告：内容长度 {} 超过 8000 字符，可能接近或超过模型上下文限制，请考虑改用全文分段处理或更大上下文模型", content.length());
        }

        // 检查API Key
        if (apiKey == null || apiKey.isEmpty()) {
            log.warn("未配置API Key，使用简化处理");
            // 如果未配置API，使用基础方法
            if ("cn".equals(sourceLang) || "zh".equals(sourceLang)) {
                result.setCnSummary(content.substring(0, Math.min(100, content.length())));
                result.setCnContent(content);
                result.setCnSentences(performBasicSegmentation(content, "cn"));
                result.setEnSummary("Translation unavailable - API Key not configured");
                result.setEnContent("Translation unavailable - API Key not configured");
                result.setEnSentences(performBasicSegmentation("Translation unavailable", "en"));
            } else {
                result.setEnSummary(content.substring(0, Math.min(100, content.length())));
                result.setEnContent(content);
                result.setEnSentences(performBasicSegmentation(content, "en"));
                result.setCnSummary("翻译不可用 - 未配置API Key");
                result.setCnContent("翻译不可用 - 未配置API Key");
                result.setCnSentences(performBasicSegmentation("翻译不可用", "cn"));
            }
            return result;
        }

        try {
            // 使用统一的提示词构建器
            String systemPrompt;
            if ("full".equalsIgnoreCase(processMode)) {
                // 全文模式提示词
                systemPrompt = ("cn".equals(sourceLang) || "zh".equals(sourceLang))
                    ? IAIService.buildChineseFullTextPrompt()
                    : IAIService.buildEnglishFullTextPrompt();
            } else {
                // 摘要模式（默认）
                systemPrompt = "cn".equals(sourceLang) || "zh".equals(sourceLang)
                    ? IAIService.buildChineseSourcePrompt()
                    : IAIService.buildEnglishSourcePrompt();
            }

            String userPrompt = content;

            // 调用API
            String response = callQwenAPI(systemPrompt, userPrompt);

            // 解析响应
            parseAndFillBilingualResult(response, result, sourceLang);

            log.info("双语摘要生成完成 - 中文摘要长度: {}, 英文摘要长度: {}",
                     result.getCnSummary() != null ? result.getCnSummary().length() : 0,
                     result.getEnSummary() != null ? result.getEnSummary().length() : 0);

            return result;

        } catch (Exception e) {
            log.error("生成双语摘要失败，使用降级方案", e);
            // 降级方案：使用原有方法逐个调用
            return generateBilingualSummaryFallback(content, sourceLang);
        }
    }

    @Override
    public BilingualSummary generateBilingualSummary(String content, String sourceLang, String processMode) {
        log.info("生成双语（带模式） - 源语言: {}, 模式: {}, 内容长度: {}", sourceLang, processMode, content.length());
        if (processMode == null || processMode.isEmpty()) {
            processMode = "summary";
        }
        
        // 全文模式：只翻译 + 代码断句（避免AI任务过重导致超时或输出不完整）
        if ("full".equalsIgnoreCase(processMode)) {
            return generateFullTextBilingual(content, sourceLang);
        }
        
        // 摘要模式：使用AI生成摘要+断句
        try {
            // 使用统一的提示词构建器
            String systemPrompt = ("cn".equals(sourceLang) || "zh".equals(sourceLang))
                ? IAIService.buildChineseSourcePrompt()
                : IAIService.buildEnglishSourcePrompt();
            
            String response = callQwenAPI(systemPrompt, content);
            BilingualSummary result = new BilingualSummary();
            parseAndFillBilingualResult(response, result, sourceLang);
            return result;
        } catch (Exception e) {
            log.error("生成双语（带模式）失败，使用降级方案", e);
            return generateBilingualSummaryFallback(content, sourceLang);
        }
    }

    /**
     * 解析AI响应并填充结果（基于文本分隔符）
     */
    private void parseAndFillBilingualResult(String response, BilingualSummary result, String sourceLang) {
        try {
            String cleanResponse = response.trim();

            // 移除可能的markdown代码块标记
            if (cleanResponse.startsWith("```")) {
                int firstNewline = cleanResponse.indexOf('\n');
                if (firstNewline > 0) {
                    cleanResponse = cleanResponse.substring(firstNewline + 1);
                }
            }
            if (cleanResponse.endsWith("```")) {
                cleanResponse = cleanResponse.substring(0, cleanResponse.lastIndexOf("```"));
            }
            cleanResponse = cleanResponse.trim();

            log.debug("开始解析AI响应（前200字符）: {}",
                     cleanResponse.length() > 200 ? cleanResponse.substring(0, 200) + "..." : cleanResponse);

            // 提取中文简短摘要（用于卡片展示）
            String cnSummary = extractSection(cleanResponse, "===中文简短摘要===", "===中文详细内容===");
            if (cnSummary == null) {
                // 向后兼容：尝试旧格式
                cnSummary = extractSection(cleanResponse, "===中文摘要===", "===中文详细内容===");
                if (cnSummary == null) {
                    cnSummary = extractSection(cleanResponse, "===Chinese Brief Summary===", "===Chinese Detailed Content===");
                }
            }
            result.setCnSummary(cnSummary != null ? cnSummary.trim() : "");

            // 提取中文详细内容（用于TTS语音）
            String cnContent = extractSection(cleanResponse, "===中文详细内容===", "<<<中文句子>>>");
            if (cnContent == null) {
                // 向后兼容：尝试英文标记
                cnContent = extractSection(cleanResponse, "===Chinese Detailed Content===", "<<<Chinese Sentences>>>");
            }
            result.setCnContent(cnContent != null ? cnContent.trim() : result.getCnSummary());

            // 提取中文句子（基于详细内容）
            String cnSentencesText = extractSection(cleanResponse, "<<<中文句子>>>", "===英文简短摘要===");
            if (cnSentencesText == null) {
                cnSentencesText = extractSection(cleanResponse, "<<<Chinese Sentences>>>", "===English Brief Summary===");
                if (cnSentencesText == null) {
                    // 向后兼容：尝试旧格式
                    cnSentencesText = extractSection(cleanResponse, "<<<中文句子>>>", "===英文摘要===");
                    if (cnSentencesText == null) {
                        cnSentencesText = extractSection(cleanResponse, "<<<Chinese Sentences>>>", "===English Summary===");
                    }
                }
            }
            JSONArray cnSentencesArray = parseSentences(cnSentencesText);
            result.setCnSentences(cnSentencesArray.toJSONString());

            // 提取英文简短摘要（用于卡片展示）
            String enSummary = extractSection(cleanResponse, "===英文简短摘要===", "===英文详细内容===");
            if (enSummary == null) {
                // 向后兼容：尝试旧格式
                enSummary = extractSection(cleanResponse, "===英文摘要===", "===英文详细内容===");
                if (enSummary == null) {
                    enSummary = extractSection(cleanResponse, "===English Brief Summary===", "===English Detailed Content===");
                    if (enSummary == null) {
                        enSummary = extractSection(cleanResponse, "===English Summary===", "===English Detailed Content===");
                    }
                }
            }
            result.setEnSummary(enSummary != null ? enSummary.trim() : "");

            // 提取英文详细内容（用于TTS语音）
            String enContent = extractSection(cleanResponse, "===英文详细内容===", "<<<英文句子>>>");
            if (enContent == null) {
                enContent = extractSection(cleanResponse, "===English Detailed Content===", "<<<English Sentences>>>");
            }
            result.setEnContent(enContent != null ? enContent.trim() : result.getEnSummary());

            // 提取英文句子（基于详细内容）
            String enSentencesText = extractSectionToEnd(cleanResponse, "<<<英文句子>>>");
            if (enSentencesText == null) {
                enSentencesText = extractSectionToEnd(cleanResponse, "<<<English Sentences>>>");
            }
            JSONArray enSentencesArray = parseSentences(enSentencesText);
            result.setEnSentences(enSentencesArray.toJSONString());

            log.info("成功解析AI响应：中文摘要{}字，详细内容{}字，{}句 | 英文摘要{}字，详细内容{}字，{}句",
                     result.getCnSummary().length(), result.getCnContent().length(), cnSentencesArray.size(),
                     result.getEnSummary().length(), result.getEnContent().length(), enSentencesArray.size());

        } catch (Exception e) {
            log.error("解析AI响应失败: {}", e.getMessage(), e);
            throw new RuntimeException("解析AI响应失败", e);
        }
    }

    /**
     * 从文本中提取指定区间的内容
     */
    private String extractSection(String text, String startMarker, String endMarker) {
        int startIdx = text.indexOf(startMarker);
        if (startIdx < 0) {
            return null;
        }
        startIdx += startMarker.length();

        int endIdx = text.indexOf(endMarker, startIdx);
        if (endIdx < 0) {
            return null;
        }

        return text.substring(startIdx, endIdx).trim();
    }

    /**
     * 从文本中提取从起始标记到末尾的内容
     */
    private String extractSectionToEnd(String text, String startMarker) {
        int startIdx = text.indexOf(startMarker);
        if (startIdx < 0) {
            return null;
        }
        startIdx += startMarker.length();

        return text.substring(startIdx).trim();
    }

    /**
     * 解析句子列表（[S0]sentence\n[S1]sentence\n...）
     */
    private JSONArray parseSentences(String sentencesText) {
        JSONArray array = new JSONArray();

        if (sentencesText == null || sentencesText.trim().isEmpty()) {
            return array;
        }

        String[] lines = sentencesText.split("\n");
        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) {
                continue;
            }

            // 查找 [S数字] 标记
            if (line.startsWith("[S")) {
                int closeBracket = line.indexOf(']');
                if (closeBracket > 0) {
                    try {
                        int index = Integer.parseInt(line.substring(2, closeBracket));
                        String text = line.substring(closeBracket + 1).trim();

                        JSONObject sentenceObj = new JSONObject();
                        sentenceObj.put("index", index);
                        sentenceObj.put("text", text);
                        array.add(sentenceObj);
                    } catch (NumberFormatException e) {
                        log.warn("跳过无效的句子标记: {}", line);
                    }
                }
            }
        }

        return array;
    }

    /**
     * 全文模式处理：只翻译 + 代码断句
     * 避免AI任务过重（翻译+断句+格式化），防止超时和输出不完整
     * 
     * @param content 原文内容
     * @param sourceLang 源语言
     * @return 双语处理结果
     */
    private BilingualSummary generateFullTextBilingual(String content, String sourceLang) {
        log.info("全文模式处理 - 只翻译+代码断句（避免AI任务过重）");
        
        BilingualSummary result = new BilingualSummary();
        
        try {
            if ("cn".equals(sourceLang) || "zh".equals(sourceLang)) {
                // 中文为源语言
                log.info("中文源文本全文处理，长度: {} 字符", content.length());
                
                // 1. 中文侧：直接使用原文 + 代码断句
                result.setCnSummary("原文全文");
                result.setCnContent(content);
                result.setCnSentences(performBasicSegmentation(content, "cn"));
                
                // 2. 英文侧：分段翻译 + 代码断句
                log.info("开始翻译中文到英文...");
                String enTranslation = translateInChunks(content, "cn", "en");
                result.setEnSummary("Full text translation");
                result.setEnContent(enTranslation);
                result.setEnSentences(performBasicSegmentation(enTranslation, "en"));
                
                log.info("全文模式处理完成 - 中文: {} 字, {} 句 | 英文: {} 字, {} 句",
                         content.length(), 
                         JSON.parseArray(result.getCnSentences()).size(),
                         enTranslation.length(),
                         JSON.parseArray(result.getEnSentences()).size());
                
            } else {
                // 英文为源语言
                log.info("英文源文本全文处理，长度: {} 字符", content.length());
                
                // 1. 英文侧：直接使用原文 + 代码断句
                result.setEnSummary("Original full text");
                result.setEnContent(content);
                result.setEnSentences(performBasicSegmentation(content, "en"));
                
                // 2. 中文侧：分段翻译 + 代码断句
                log.info("开始翻译英文到中文...");
                String cnTranslation = translateInChunks(content, "en", "cn");
                result.setCnSummary("原文全文翻译");
                result.setCnContent(cnTranslation);
                result.setCnSentences(performBasicSegmentation(cnTranslation, "cn"));
                
                log.info("全文模式处理完成 - 英文: {} 字, {} 句 | 中文: {} 字, {} 句",
                         content.length(),
                         JSON.parseArray(result.getEnSentences()).size(),
                         cnTranslation.length(),
                         JSON.parseArray(result.getCnSentences()).size());
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("全文模式处理失败", e);
            // 降级：使用原文内容，不翻译
            if ("cn".equals(sourceLang) || "zh".equals(sourceLang)) {
                result.setCnSummary("处理失败");
                result.setCnContent(content);
                result.setCnSentences(performBasicSegmentation(content, "cn"));
                result.setEnSummary("Processing failed");
                result.setEnContent("Translation failed due to error");
                result.setEnSentences(performBasicSegmentation("Translation failed", "en"));
            } else {
                result.setEnSummary("Processing failed");
                result.setEnContent(content);
                result.setEnSentences(performBasicSegmentation(content, "en"));
                result.setCnSummary("处理失败");
                result.setCnContent("翻译失败");
                result.setCnSentences(performBasicSegmentation("翻译失败", "cn"));
            }
            return result;
        }
    }
    
    /**
     * 分段翻译（避免长文本超时）
     * 按段落边界切分，每段独立翻译，最后合并
     * 
     * @param content 待翻译内容
     * @param fromLang 源语言
     * @param toLang 目标语言
     * @return 翻译结果
     */
    private String translateInChunks(String content, String fromLang, String toLang) {
        // 阈值：超过2000字符进行分段
        final int CHUNK_SIZE = 2000;
        
        if (content.length() <= CHUNK_SIZE) {
            log.info("内容较短({} 字符)，一次性翻译", content.length());
            return translate(content, fromLang, toLang);
        }
        
        log.info("内容较长({} 字符)，分段翻译（每段约 {} 字符）", content.length(), CHUNK_SIZE);
        
        try {
            // 按段落切分
            List<String> chunks = splitByParagraphs(content, CHUNK_SIZE);
            log.info("已切分为 {} 段", chunks.size());
            
            StringBuilder result = new StringBuilder();
            
            for (int i = 0; i < chunks.size(); i++) {
                String chunk = chunks.get(i);
                log.info("翻译第 {}/{} 段，长度: {} 字符", i + 1, chunks.size(), chunk.length());
                
                // 翻译当前段
                String translated = translate(chunk, fromLang, toLang);
                result.append(translated);
                
                // 段落之间保留换行（最后一段除外）
                if (i < chunks.size() - 1) {
                    result.append("\n\n");
                }
                
                // 延迟避免速率限制（最后一段不延迟）
                if (i < chunks.size() - 1) {
                    try {
                        Thread.sleep(1500); // 1.5秒延迟
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        log.warn("翻译延迟被中断");
                    }
                }
            }
            
            String finalResult = result.toString().trim();
            log.info("分段翻译完成，总长度: {} 字符", finalResult.length());
            return finalResult;
            
        } catch (Exception e) {
            log.error("分段翻译失败，尝试直接翻译", e);
            // 降级：直接翻译（可能超时，但至少尝试）
            return translate(content, fromLang, toLang);
        }
    }
    
    /**
     * 按段落边界切分文本
     * 优先按双换行符（段落）切分，保证语义完整
     * 
     * @param content 原文内容
     * @param maxChunkSize 单段最大长度
     * @return 切分后的段落列表
     */
    private List<String> splitByParagraphs(String content, int maxChunkSize) {
        List<String> chunks = new ArrayList<>();
        
        // 按段落切分（双换行符或单换行符）
        String[] paragraphs = content.split("\n\n|\n");
        
        StringBuilder currentChunk = new StringBuilder();
        
        for (String para : paragraphs) {
            para = para.trim();
            if (para.isEmpty()) {
                continue;
            }
            
            // 如果当前段落加上新段落超过阈值，先保存当前段
            if (currentChunk.length() > 0 && 
                currentChunk.length() + para.length() + 2 > maxChunkSize) {
                chunks.add(currentChunk.toString().trim());
                currentChunk = new StringBuilder();
            }
            
            // 单个段落本身就超过阈值，需要按句子切分
            if (para.length() > maxChunkSize) {
                // 如果当前有累积内容，先保存
                if (currentChunk.length() > 0) {
                    chunks.add(currentChunk.toString().trim());
                    currentChunk = new StringBuilder();
                }
                
                // 按句号切分超长段落
                String[] sentences = para.split("(?<=[。！？.!?])");
                for (String sentence : sentences) {
                    if (currentChunk.length() + sentence.length() > maxChunkSize && currentChunk.length() > 0) {
                        chunks.add(currentChunk.toString().trim());
                        currentChunk = new StringBuilder();
                    }
                    currentChunk.append(sentence);
                }
            } else {
                // 段落未超阈值，追加到当前块
                if (currentChunk.length() > 0) {
                    currentChunk.append("\n\n");
                }
                currentChunk.append(para);
            }
        }
        
        // 保存最后一段
        if (currentChunk.length() > 0) {
            chunks.add(currentChunk.toString().trim());
        }
        
        // 如果切分失败，整个作为一段
        if (chunks.isEmpty()) {
            chunks.add(content);
        }
        
        return chunks;
    }

    /**
     * 降级方案：使用原有方法逐个调用
     * 注意：降级方案需要区分简短摘要和详细内容
     */
    private BilingualSummary generateBilingualSummaryFallback(String content, String sourceLang) {
        log.info("使用降级方案生成双语摘要（区分简短摘要和详细内容）");

        BilingualSummary result = new BilingualSummary();

        try {
            if ("cn".equals(sourceLang) || "zh".equals(sourceLang)) {
                // 中文为源语言
                // 1. 生成简短摘要（100字）
                String cnSummary = generateSummary(content, "cn");
                result.setCnSummary(cnSummary);

                // 2. 生成详细内容（取原文前300字作为详细内容，确保比摘要更详细）
                String cnContent = content.length() > 300 ? content.substring(0, 300) + "..." : content;
                result.setCnContent(cnContent);

                // 3. 基于详细内容进行断句
                result.setCnSentences(smartSegmentation(cnContent, "cn"));

                // 4. 翻译简短摘要到英文
                String enSummary = translate(cnSummary, "cn", "en");
                result.setEnSummary(enSummary);

                // 5. 翻译详细内容到英文
                String enContent = translate(cnContent, "cn", "en");
                result.setEnContent(enContent);

                // 6. 基于英文详细内容断句
                result.setEnSentences(smartSegmentation(enContent, "en"));

                log.info("降级方案成功：中文摘要{}字，详细内容{}字 | 英文摘要{}字，详细内容{}字",
                         cnSummary.length(), cnContent.length(), enSummary.length(), enContent.length());
            } else {
                // 英文为源语言
                // 1. 生成简短摘要（100字）
                String enSummary = generateSummary(content, "en");
                result.setEnSummary(enSummary);

                // 2. 生成详细内容（取原文前300字）
                String enContent = content.length() > 300 ? content.substring(0, 300) + "..." : content;
                result.setEnContent(enContent);

                // 3. 基于详细内容断句
                result.setEnSentences(smartSegmentation(enContent, "en"));

                // 4. 翻译简短摘要到中文
                String cnSummary = translate(enSummary, "en", "cn");
                result.setCnSummary(cnSummary);

                // 5. 翻译详细内容到中文
                String cnContent = translate(enContent, "en", "cn");
                result.setCnContent(cnContent);

                // 6. 基于中文详细内容断句
                result.setCnSentences(smartSegmentation(cnContent, "cn"));

                log.info("降级方案成功：英文摘要{}字，详细内容{}字 | 中文摘要{}字，详细内容{}字",
                         enSummary.length(), enContent.length(), cnSummary.length(), cnContent.length());
            }
        } catch (Exception e) {
            log.error("降级方案也失败了", e);
            // 最终降级：使用原始内容的缩略
            String fallbackContent = content.length() > 300 ? content.substring(0, 300) : content;
            result.setCnSummary("AI处理失败，显示原文摘要");
            result.setCnContent(fallbackContent);
            result.setCnSentences(performBasicSegmentation(fallbackContent, "cn"));
            result.setEnSummary("AI processing failed, showing original text summary");
            result.setEnContent(fallbackContent);
            result.setEnSentences(performBasicSegmentation(fallbackContent, "en"));
        }

        return result;
    }

    @Override
    public boolean testConnection() {
        log.info("测试阿里云通义千问连接");

        if (apiKey == null || apiKey.isEmpty()) {
            log.warn("未配置API Key，连接测试失败");
            return false;
        }

        try {
            // 发送简单的测试请求
            String testPrompt = "Hello";
            String response = callQwenAPI(null, testPrompt);

            if (response != null && !response.isEmpty()) {
                log.info("通义千问API连接测试成功");
                return true;
            } else {
                log.warn("通义千问API返回为空");
                return false;
            }
        } catch (Exception e) {
            log.error("连接测试失败", e);
            return false;
        }
    }
}

